<?php
/**
 * <pre>
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT      : rubik-base
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * [GENERAL INFO OF THIS FILE] 
 *
 * </pre>
 * 
 * @version 		1.0
 * @author			Dang Nhon Hoa <hoadn@rubik.com.vn>
 * @access			public
 * @package			rubik.base.html
 *
 * Created on	: May 25, 2008
 */
RCoreImporter::cls("helper.RFileFolderHelper" );

class AbstractHtmlUploadForm {
	
	/**
	 * The input name of this control
	 *
	 * @var string
	 */
	var $_inputName = null;
	
	/**
	 * All supported type for this UploadForm
	 * Ex: ".mp3, .swf, .wma"
	 * 
	 * @var string
	 */
	var $_supportedTypes = null;
	
	/**
	 * Value of this component
	 *
	 * @var string
	 */
	var $_value = null;
	
	/**
	 * Path from root. The path to place file from the root
	 *
	 * @var string
	 */
	var $_pathFromRoot = null;
	
	/**
	 * Error Message
	 *
	 * @var string
	 */
	var $_errorMsg = null;
	
	/**
	 * Create thumb or nnot
	 *
	 * @var boolean
	 */
	var $_bCreateThumb;
	
	/**
	 * Width of thumb
	 *
	 * @var int
	 */
	var $_Width;
	
	/**
	 * Height of thumb
	 *
	 * @var int
	 */
	var $_Height;
	
	/**
	 * Get Name
	 *
	 * @var boolean
	 */
	var $bgetName;
	/**
	 * Construtor
	 *
	 * @param string $inputName
	 * @param string $pathFromRoot Ex: "uploadFiles/images/"
	 * @param string/array $valueOrArrayContain if array normaly it should be: $_GET, $_POST, $_REQUEST
	 * @param string $supportedTypes Ex: ".mp3, .swf, .wma" 
	 * @return AbstractHtmlUploadForm
	 */
	function __construct($inputName, $pathFromRoot, $valueOrArrayContain = null, $supportedTypes = null, $bThumb = false, $iWidth = 0, $iHeight = 0, $bName = false) {
		$this->_inputName = $inputName;
		$this->_supportedTypes = $supportedTypes;
		$this->_pathFromRoot = $pathFromRoot;
		$this->_bCreateThumb = $bThumb;
		$this->_Width = $iWidth;
		$this->_Height = $iHeight;
		$this->bgetName = $bName;
		$this->setValue ( $valueOrArrayContain );
	}
	
	/**
	 * Set value for this
	 *
	 * @param string/array $valueOrArrayContain
	 */
	function setValue($valueOrArrayContain) {
		$dirUrl = SYS_ROOT_PATH . "files/";
		if (! is_array ( $valueOrArrayContain )) {
			$this->_value = $valueOrArrayContain;
			return;
		}
		
		$inputName = $this->_inputName;
		$changeName = $inputName . '_change';
		$oldName = $inputName . '_old_value';
		
		$oldLink = $valueOrArrayContain [$oldName];
		$changValue = $valueOrArrayContain [$changeName];
		$folder = $dirUrl . $this->_pathFromRoot . "/";
		if ($changValue == 'file') {
			if (strpos ( $oldLink, "://" ) === false) {
				@unlink ( $folder . $oldLink );
				@unlink ( $folder . "thumb/" . $oldLink );
				@unlink ( $oldLink );
				@unlink ( "../".$oldLink );
			}
			$file_name = $_FILES [$inputName] ['name'];
			$temp_file = $_FILES [$inputName] ['tmp_name'];
			//$folder = $dirUrl.$this->_pathFromRoot."/";//$this->getAbsRootPath().$this->_pathFromRoot;
			$sUploadValue = RFileFolderHelper::uploadFile ( $temp_file, $file_name, $folder, $this->_supportedTypes );
			
			if ($sUploadValue === false) {
				$this->_errorMsg = 'Upload picture error!';
			} else {
				$abcd = $sUploadValue;
				$sUploadValue = $folder . $sUploadValue;
				if ($this->_bCreateThumb === true) {
					$this->createThumb ( $sUploadValue, $this->_Width, $this->_Height, $folder . "thumb/" . $abcd );
				}
			
			}
		} elseif ($changValue == 'url') {
			@unlink ( $this->getAbsRootPath () . $oldLink );
			$sUploadValue = $valueOrArrayContain [$inputName];
		} else {
			$sUploadValue = $oldLink;
		}
		if ($this->bgetName === true) {
			$this->_value = $abcd;
			return $abcd;
		} else {
			$this->_value = $sUploadValue;
			return $sUploadValue;
		}
	}
	
	/**
	 * Create the HTML text for doing upload
	 *
	 * @param int $inputSize view size of html
	 * @param string $cssCls
	 * @return string: html string
	 */
	function createUploadFormHtml($inputSize) {
		static $id;
		if (empty ( $id )) {
			$id = 1;
			// print the check javascript for the first time
			$script = '<script type="text/javascript">
			<!--
			function checkUploadTypeForm (inputId, inputName) {
				var icheck = document.getElementById(inputId+"_status");
				var iurl = document.getElementById(inputId+"_link");
				var ifile = document.getElementById(inputId+"_file");
				var ivalidate = document.getElementById(inputName+"_ok");
				ivalidate.value = \'empty\';
				if (icheck.checked == true) {
					iurl.style.display = \'none\';
					ifile.style.display = \'block\';
				} else {
					iurl.style.display = \'block\';
					ifile.style.display = \'none\';
				}
			}
			
			function checkValidFileTypeFroUpload(InputId, inputType, ele , acceptFileType) {
				if (acceptFileType == \'\' || acceptFileType == undefined) {
					return true;
				} 
				var ichange = document.getElementById(InputId+"_change");
				var ivalidate = document.getElementById(InputId+"_ok");
				ivalidate.value = \'no\';	
				if (inputType == "text") {
					ichange.value = \'url\';
				} else if (inputType == "file") {
					ichange.value = \'file\';
				}
			
				testString = ele.value;
				testString = testString.toLowerCase();;
				
				arrType = acceptFileType.toLowerCase().split(",");
				
				size = arrType.length;
				for (i = 0; i < size; i++) {
					ext = trim(arrType[i]);
					if (ext != "" && testString.lastIndexOf(ext) != -1){
						ivalidate.value = \'yes\';
						return true;
					}
				}
			
				if (inputType == "text") {
					alert("Your input url type should in: " + acceptFileType);
				} else if (inputType == "file") {
					alert("Your input file type should in: " + acceptFileType);
				}
				emptyValue(ele);
				ivalidate.value = \'no\';
				ele.focus();
				return false;
			}
			//-->
			</script>';
		}
		$inputName = $this->_inputName;
		$supportFileTypes = $this->_supportedTypes;
		$value = $this->_value;
		
		$strCommentTypeUpload = "";
		$strCommentTypeUpload = "<em>(Only accept file type: $supportFileTypes) </em>";
		$inputId = $inputName . $id;
		
		if (! strpos ( $value, '://' ) && $value != '') {
			$value = $this->getRootUrlPath () . $value;
		}
		if (empty ( $this->_value )) {
			$ivalidatevalue = 'no';
		} else {
			$ivalidatevalue = 'yes';
		}
		$sout = $script . '<div  style="float: left;"><input type="checkbox" name="' . $inputName . '_status" id="' . $inputId . '_status" value="1" onclick="checkUploadTypeForm(\'' . $inputId . '\',\'' . $inputName . '\');"> </div>';
		$sout .= '<div id="' . $inputId . '_link"><input name="' . $inputName . '" id="' . $inputName . '_link" type="text" value="' . $value . '" size="' . $inputSize . '" onchange="checkValidFileTypeFroUpload(\'' . $inputName . '\',\'text\',this,\'' . $supportFileTypes . '\');" /></div>';
		$sout .= '<div id="' . $inputId . '_file" style="display:none"><input name="' . $inputName . '" id="' . $inputName . '_file" type="file" onchange="checkValidFileTypeFroUpload(\'' . $inputName . '\',\'file\',this,\'' . $supportFileTypes . '\');" size="' . $inputSize . '" /></div>';
		$sout .= '<input type="hidden" name="' . $inputName . '_change" id="' . $inputName . '_change" value="nochange" />';
		$sout .= '<input type="hidden" name="' . $inputName . '_old_value" id="' . $inputName . '_old_value" value="' . $this->_value . '" />';
		$sout .= '<input type="hidden" name="' . $inputName . '_ok" id="' . $inputName . '_ok" value="' . $ivalidatevalue . '" />';
		$sout .= $strCommentTypeUpload;
		$id ++;
		return $sout;
	}
	
	/**
	 * Get the originally value of this.
	 *
	 * @return string
	 */
	function getOriginallyValue() {
		return $this->_value;
	}
	
	/**
	 * Get the value without link to current site
	 *
	 * @return string
	 */
	function getValueWithoutUrl() {
		$value = $this->_value;
		$value = str_replace ( $this->getRootUrlPath (), "", $value );
		$value = str_replace ( $this->getAbsRootPath (), "", $value );
		return $value;
	}
	
	/**
	 * Get the root URL
	 * Ex: "http://rubik.com.vn/application"
	 * 
	 * @abstract this function must be overide by subClass
	 *
	 * @return string the http:// path of current site
	 */
	function getRootUrlPath() {
		error_log ( "This function must be override by the sub class" );
	}
	
	/**
	 * Get the absolute path of root folder
	 * Ex: "D:\www\rubik\application"
	 * @abstract this function must be overide by subClass
	 *
	 * @return string the  path of current site
	 */
	function getAbsRootPath() {
		error_log ( "This function must be override by the sub class" );
	}
	
	/**
	 * create Thumb nail!
	 *
	 * @param string $filename
	 * @param string $dirSave
	 * @param int $max_width
	 * @param int $max_height
	 * @param string $newfilename
	 */
	
	function createThumb($filename, $max_width, $max_height = '', $newfilename = "", $withSampling = true) {
		if ($newfilename == "")
			$newfilename = $filename;
			// Get new sizes
		list ( $width, $height ) = getimagesize ( $filename );
		
		//-- dont resize if the width of the image is smaller or equal than the new size.
		if ($width <= $max_width)
			$max_width = $width;
		
		$percent = $max_width / $width;
		
		$newwidth = $width * $percent;
		if ($max_height == '') {
			$newheight = $height * $percent;
		} else
			$newheight = $max_height;
			
		// Load
		$thumb = imagecreatetruecolor ( $newwidth, $newheight );
		$ext = strtolower ( $this->getExtension ( $filename ) );
		if ($ext == 'jpg' || $ext == 'jpeg')
			$source = imagecreatefromjpeg ( $filename );
		if ($ext == 'gif')
			$source = imagecreatefromgif ( $filename );
		if ($ext == 'png')
			$source = imagecreatefrompng ( $filename );
			
		// Resize
		if ($withSampling)
			imagecopyresampled ( $thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
		else
			imagecopyresized ( $thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
			
		// Output
		if ($ext == 'jpg' || $ext == 'jpeg')
			return imagejpeg ( $thumb, $newfilename );
		if ($ext == 'gif')
			return imagegif ( $thumb, $newfilename );
		if ($ext == 'png')
			return imagepng ( $thumb, $newfilename );
	}
	
	function getExtension($str) {
		
		$rVal = "";
		$pos = strrpos ( $str, "." );
		if ($pos !== false) {
			$rVal = substr ( $str, ($pos + 1) );
		}
		return $rVal;
	
	}

}
?>